package org.lzy.shop.network

import android.net.Uri
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.request.get
import io.ktor.client.request.post
import io.ktor.client.request.setBody
import io.ktor.http.ContentType
import io.ktor.http.HttpHeaders
import io.ktor.http.contentType
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import org.json.JSONObject
import org.lzy.shop.Constant
import org.lzy.shop.base.BaseResponse
import org.lzy.shop.datas.AddAddressRequest
import org.lzy.shop.datas.DelAddress
import org.lzy.shop.datas.EditAddressRequest
import org.lzy.shop.datas.FeedBackSubmitRequest
import org.lzy.shop.datas.OrderCommentRequest
import org.lzy.shop.datas.OrderRequest
import org.lzy.shop.datas.SubmitOrderNewRequest
import org.lzy.shop.response.AddressResponse
import org.lzy.shop.response.CommentResponse
import org.lzy.shop.response.ConifimOrderResponse
import org.lzy.shop.response.CouponResponse
import org.lzy.shop.response.CreateMsgResponse
import org.lzy.shop.response.CustomerMsgResponse
import org.lzy.shop.response.DataReasonResponse
import org.lzy.shop.response.FeedBackResponse
import org.lzy.shop.response.FeedBackTypeResponse
import org.lzy.shop.response.GoodsInfoResponse
import org.lzy.shop.response.GoodsSpecResponse
import org.lzy.shop.response.HomeClassifyResponse
import org.lzy.shop.response.HomeGoodAllResponse
import org.lzy.shop.response.HomeResponse
import org.lzy.shop.response.LoginResponse
import org.lzy.shop.response.LogisticsResponse
import org.lzy.shop.response.MyInfoResponse
import org.lzy.shop.response.OrderInfoResponse
import org.lzy.shop.response.OrderResponse
import org.lzy.shop.response.OssUpload
import org.lzy.shop.response.PicSmsResponse
import org.lzy.shop.response.SearchGoodsResponse
import org.lzy.shop.response.SearchResponse
import org.lzy.shop.response.SubmitOrderSuccessResponse
import org.lzy.shop.response.UserCountResponse
import org.lzy.shop.util.DataStoreUtils

/**
 * Ktor 接口管理服务，用于替代Retrofit实现所有网络请求
 */
object KtorApiService {
    private lateinit var httpClient: HttpClient

    fun init(client: HttpClient) {
        httpClient = client
    }

    /**
     * 封装GET和POST请求的通用逻辑，包括添加认证头、设置请求参数、处理请求体等，并返回BaseResponse
     * @param method 请求方式 POST还是Get
     * @param path 请求地址路径
     * @param body 请求参数体
     * @param requireAuth 头部token请求，默认为true
     * @param params 请求用map，这个看需不需要
     */
    private val json = Json {
        // 宽松模式：允许解析格式不严格的JSON
        isLenient = true
        // 忽略未知键
        ignoreUnknownKeys = true
        // 允许将空字符串解析为null
        coerceInputValues = true
        // 序列化null值
        encodeDefaults = true

    }

    private suspend inline fun <reified T> apiRequest(
        method: String,
        path: String,
        body: Any? = null,
        requireAuth: Boolean = true,
        params: Map<String, String>? = null
    ): BaseResponse<T> {
        return withContext(Dispatchers.IO) {
            when (method) {
                "GET" -> httpClient.get("${Constant.BASE_URL}$path") {
                    if (requireAuth) headers.append(HttpHeaders.Authorization, DataStoreUtils.getToken(Constant.TOKEN))
                    params?.forEach { (key, value) -> url.parameters.append(key, value) }
                }.body()
                "POST" -> httpClient.post("${Constant.BASE_URL}$path") {
                    if (requireAuth) headers.append(HttpHeaders.Authorization, DataStoreUtils.getToken(Constant.TOKEN))
                    contentType(ContentType.Application.Json)
                    body?.let { setBody(it) }
                    params?.forEach { (key, value) -> url.parameters.append(key, value) }
                }.body()
                else -> throw IllegalArgumentException("Unsupported HTTP method")
            }
        }
    }


    /**
     * 登录
     */
    suspend fun login(phone: String, password: String): BaseResponse<LoginResponse> {
        return apiRequest("POST", "app/user/login/password",LoginRequest(phone,password))
    }

    @Serializable
    data class LoginRequest(val phone: String, val password: String)

    /**
     * QQ授权登录
     */
    suspend fun loginQQ(accessToken: String, openId: String): BaseResponse<LoginResponse> {
        return apiRequest("POST", "app/user/login/qq",LoginQQRequest(accessToken,openId))
    }


    @Serializable
    data class LoginQQRequest(val accessToken: String, val openId: String)



    /**
     * 短信登录
     */
    suspend fun loginSms(phone: String, code: String): BaseResponse<LoginResponse> {
        val jsonObject = JSONObject()
        jsonObject.put("phone", phone)
        jsonObject.put("smsCode", code)
        return apiRequest("POST", "app/user/login/phone",LoginSmsRequest(phone,code))

    }

    @Serializable
    data class LoginSmsRequest(val phone: String, val smsCode: String)

    /**
     * 刷新token
     */
    suspend fun refreshToken(refreshToken: String): BaseResponse<LoginResponse> {
        val jsonObject = JSONObject()
        jsonObject.put("refreshToken", refreshToken)
        return apiRequest("POST", "app/user/login/refreshToken",jsonObject.toString())
    }

    /**
     * 获取图片验证码
     */
    suspend fun getPicSms(): BaseResponse<PicSmsResponse> {
        return apiRequest(method = "GET", path = "app/user/login/captcha", requireAuth = false, params = mapOf(
            "type" to "blockPuzzle",
            "width" to "150",
            "height" to "50"
        )
        )
    }

    /**
     * 发送短信验证码
     */
    suspend fun sendSms(phone: String, captchaId: String, code: String): BaseResponse<String> {
        return apiRequest("POST", "app/user/login/smsCode",SendSmsRequest(phone,captchaId,code))

    }

    @Serializable
    data class SendSmsRequest(val phone: String, val captchaId: String, val code: String)

    /**
     * 用户注册
     */
    suspend fun register(phone: String, smsCode: String, password: String, confirmPassword: String): BaseResponse<String> {
        return apiRequest("POST", "app/user/register",RegisterRequest(phone,smsCode,password,confirmPassword))

    }

    @Serializable
    data class RegisterRequest(val phone: String, val smsCode: String, val password: String, val confirmPassword: String)

    /**
     * 刷新Token
     */
    suspend fun refreshToken(request: RefreshTokenRequest): RefreshTokenResponse? {
        return withContext(Dispatchers.IO) {
            try {
                httpClient.post("${Constant.BASE_URL}app/user/login/refreshToken") {
                    contentType(ContentType.Application.Json)
                    setBody(request)
                }.body()
            } catch (e: Exception) {
                null
            }
        }
    }

    /**
     * 获取首页数据
     */
    suspend fun home(): BaseResponse<HomeResponse> {
        return apiRequest("GET", "app/page/home")
    }

    /**
     * 获取首页分类数据
     */
    suspend fun getHomeClassify(): BaseResponse<MutableList<HomeClassifyResponse>> {
        return apiRequest("POST", "app/goods/type/list")
    }

    /**
     * 获取我的信息
     */
    suspend fun getMyInfo(): BaseResponse<MyInfoResponse> {
        return apiRequest("GET", "app/user/info/person")
    }

    /**
     * 获取订单数量
     */
    suspend fun getUserCount(): BaseResponse<UserCountResponse> {
        return apiRequest("GET", "app/order/info/userCount")
    }

    /**
     * 获取商品详情
     */
    suspend fun getGoodsInfo(goodsId: String?): BaseResponse<GoodsInfoResponse> {
        val params = goodsId?.takeIf { it.isNotBlank() }?.let {
            mapOf("goodsId" to it)
        }
        return apiRequest(method = "GET", path = "app/page/goodsDetail", requireAuth = false, params = params)
    }


    /**
     * 获取商品规格
     */
    suspend fun getGoodsSpec(goodsId: String): BaseResponse<MutableList<GoodsSpecResponse>> {
        val jsonObject = JSONObject()
        jsonObject.put("goodsId", goodsId)
        return apiRequest("POST", "app/goods/spec/list",jsonObject.toString())
    }

    /**
     * 创建订单
     */
    suspend fun createOrder(request: SubmitOrderNewRequest): BaseResponse<SubmitOrderSuccessResponse> {
        return apiRequest("POST", "app/order/info/create")
    }

    /**
     * 获取默认地址
     */
    suspend fun getDefaultAddress(): BaseResponse<AddressResponse> {
        return apiRequest("GET", "app/user/address/default")
    }

    /**
     * 获取地址列表
     */
    suspend fun getAddressList(): BaseResponse<MutableList<AddressResponse>> {
        return apiRequest("POST", "app/user/address/list")
    }

    /**
     * 添加地址
     */
    suspend fun addAddress(request: AddAddressRequest): BaseResponse<String> {
        return apiRequest("POST", "app/user/address/add")
    }

    /**
     * 更新地址
     */
    suspend fun updateAddress(request: EditAddressRequest): BaseResponse<String> {
        return apiRequest("POST", "app/user/address/update")
    }

    /**
     * 删除地址
     */
    suspend fun delAddress(request: DelAddress): BaseResponse<String> {
        return apiRequest("POST", "app/user/address/delete")
    }

    /**
     * 获取优惠券列表
     */
    suspend fun getCoupon(): BaseResponse<CouponResponse> {
        return apiRequest("POST", "app/market/coupon/info/page")
    }

    /**
     * 获取我的优惠券
     */
    suspend fun getMyCoupon(page: Int, size: Int): BaseResponse<CouponResponse> {
        return apiRequest("POST", "app/market/coupon/user/page",MyCouponRequest(page, size ,"desc"))
    }

    @Serializable
    data class MyCouponRequest(val page: Int, val size: Int?, val sort: String?)

    /**
     * 领取优惠券
     */
    suspend fun couponReceive(couponId: Int?): BaseResponse<String> {
        return apiRequest("POST", "app/market/coupon/user/receive", CouponReceiveRequest(couponId))
    }

    @Serializable
    data class CouponReceiveRequest(val couponId: Int?)

    /**
     * 获取订单列表
     */
    suspend fun getOrder(orderRequest: OrderRequest): BaseResponse<OrderResponse> {
        return apiRequest("POST", "app/order/info/page", orderRequest)
    }

    /**
     * 获取确认订单页面数据
     */
    suspend fun confirmOrder(): BaseResponse<ConifimOrderResponse> {
        return apiRequest("GET", "app/page/confirmOrder")
    }

    /**
     * 支付
     */
    suspend fun pay(orderId: Int, payType: Int): BaseResponse<String> {
        return apiRequest("POST", "app/order/pay/alipayAppPay", PayRequest(orderId,payType))
    }

    @Serializable
    data class PayRequest(val orderId: Int?,val payType: Int?)

    /**
     * 查看物流
     */
    suspend fun getLogistics(orderId: Int?): BaseResponse<LogisticsResponse> {
        val params = orderId?.let { mapOf("orderId" to it.toString()) }
        return apiRequest("GET", "app/order/info/logistics", params = params)
    }

    /**
     * 取消订单
     */
    suspend fun cancelOrder(orderId: Int, remark: String? = null): BaseResponse<String> {
        return apiRequest("POST", "app/order/info/cancel", CancelOrderRequest(orderId, remark))
    }

    @Serializable
    data class CancelOrderRequest(val orderId: Int, val remark: String?)

    /**
     * 订单退款
     */
    suspend fun refundOrder(orderId: Int, reason: String?): BaseResponse<Any> {
        return apiRequest("POST", "app/order/info/refund", RefundOrderRequest(orderId, reason))
    }

    @Serializable
    data class RefundOrderRequest(val orderId: Int, val reason: String?)

    /**
     * 获取订单详情
     */
    suspend fun getOrderInfo(id: Int?): BaseResponse<OrderInfoResponse> {
        val params = id?.let { mapOf("id" to it.toString()) }
        return apiRequest("GET", "app/order/info/info", params = params)
    }

    /**
     * 确认收货
     */
    suspend fun confirmOrder(orderId: Int?): BaseResponse<String> {
        val params = orderId?.let { mapOf("orderId" to it.toString()) }
        return apiRequest("GET", "app/order/info/confirm", params = params)
    }

    /**
     * 获取退款理由数据
     */
    suspend fun getReasonData(): BaseResponse<DataReasonResponse> {
        return apiRequest("POST", "app/dict/info/data", DictDataRequest(listOf("orderRefundReason")))
    }

    @Serializable
    data class DictDataRequest(val types: List<String>)

    /**
     * 获取反馈类型
     */
    suspend fun getReasonFeedBack(): BaseResponse<FeedBackTypeResponse> {
        return apiRequest("POST", "app/dict/info/data", DictDataRequest(listOf("feedbackType")))
    }

    /**
     * 获取上传文件地址
     */
    suspend fun getUploadCredentials(): BaseResponse<OssUpload> {
        return apiRequest("POST", "app/base/comm/upload")
    }

    /**
     * 提交评论
     */
    suspend fun orderComment(request: OrderCommentRequest): BaseResponse<Any> {
        return apiRequest("POST", "app/order/comment/create", request)
    }

    /**
     * 获取主页所有商品
     */
    suspend fun getHomeGoodsAll(): BaseResponse<HomeGoodAllResponse> {
        return apiRequest("POST", "app/goods/info/page")
    }

    /**
     * 注销账户
     */
    suspend fun logoff(): BaseResponse<Any> {
        return apiRequest("GET", "app/user/info/logoff")
    }

    /**
     * 创建消息会话
     */
    suspend fun createMsg(): BaseResponse<CreateMsgResponse> {
        return apiRequest("POST", "app/cs/session/create")
    }

    /**
     * 获取消息列表
     */
    suspend fun getMsgList(sessionId: Int?, page: String?): BaseResponse<CustomerMsgResponse> {
        val jsonObject = JSONObject()
        jsonObject.put("sessionId", sessionId)
        jsonObject.put("page", page)
        jsonObject.put("size", 10)
        jsonObject.put("order", "createTime")
        jsonObject.put("sort", "desc")
        return apiRequest("POST", "app/cs/msg/page", jsonObject.toString())
    }

    @Serializable
    data class MsgListRequest(val sessionId: Int, val page: String?,val size: Int?,val order: String?,val sort: String?)

    /**
     * 发送消息
     */
    suspend fun sendMessage(sessionId: Int?, content: String): BaseResponse<Any> {
        return apiRequest("POST", "app/cs/msg/send", sendMessageRequest(sessionId, content ,"text"))
    }

    @Serializable
    data class sendMessageRequest(val sessionId: Int?, val content: String?,val type: String?)

    /**
     * 上传单张图片到腾讯云
     */
    suspend fun uploadImageToTencent(imageUri: Uri, uploadUrl: String, tmpSecretId: String, tmpSecretKey: String, sessionToken: String): BaseResponse<String> {
        // 注意：实际项目中需要实现真实的图片上传逻辑
        // 这里返回一个模拟的成功响应
        return BaseResponse(data = "uploaded_image_url", message = "")
    }

    /**
     * 批量上传图片到腾讯云
     */
    suspend fun uploadImagesToTencent(imageUris: List<Uri>, uploadUrl: String, tmpSecretId: String, tmpSecretKey: String, sessionToken: String): BaseResponse<List<String>> {
        // 注意：实际项目中需要实现真实的图片上传逻辑
        // 这里返回一个模拟的成功响应
        val uploadedUrls = mutableListOf<String>()
        imageUris.forEachIndexed {
                index, _ -> uploadedUrls.add("uploaded_image_url_$index")
        }
        return BaseResponse(data = uploadedUrls, message = "")
    }

    /**
     * 获取商品评价
     */
    suspend fun getGoodsComment(page: Int, size: Int, goodsId: String?): BaseResponse<CommentResponse> {
        return apiRequest("POST", "app/goods/comment/page", GoodsCommentRequest(page, size, goodsId))
    }

    @Serializable
    data class GoodsCommentRequest(val page: Int, val size: Int, val goodsId: String?)



    /**
     * 搜索商品
     */
    suspend fun getSearchResult(
        keyword: String,
        page: Int,
        typeId: ArrayList<Int>? = null,
        order: String,
        sort: String
    ): BaseResponse<SearchGoodsResponse> {
        return apiRequest("POST", "app/goods/info/page", SearchResultRequest(keyword, page, 10, typeId, order, sort))
    }

    @Serializable
    data class SearchResultRequest(
        val keyword: String,
        val page: Int,
        val size: Int,
       val typeId: ArrayList<Int>?, // 从List<String>?改为JSONArray?
        val order: String,
        val sort: String
    )

    /**
     * 获取反馈列表
     */
    suspend fun getFeedBack(page: Int): BaseResponse<FeedBackResponse> {
        return apiRequest("POST", "app/app/feedback/page", FeedBackListRequest(page, 10))
    }

    @Serializable
    data class FeedBackListRequest(val page: Int, val size: Int)

    /**
     * 提交反馈
     */
    suspend fun feedbackSubmit(request: FeedBackSubmitRequest): BaseResponse<Any> {
        return apiRequest("POST", "app/app/feedback/submit", request)
    }

    /**
     * 获取热门搜索
     */
    suspend fun getSearchHot(): BaseResponse<MutableList<SearchResponse>> {
        return apiRequest("POST", "app/goods/search/keyword/list")
    }


}